<template>
	<div class="layout-padding">
		<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto" v-loading="loading">
			<el-card>
				<template #header>
					<div class="card-header">
						<span>基础信息设置</span>
						<el-button type="primary" @click="onSubmit">提交</el-button>
					</div>
				</template>

				<el-row :gutter="30">
					<el-col :span="12">
						<div class="form-container">
							<el-form-item label="公司名称" prop="companyName">
								<el-input v-model="formData.companyName" placeholder="请输入公司名称" clearable />
							</el-form-item>
							<el-form-item label="联系电话" prop="contactPhone">
								<el-input v-model="formData.contactPhone" placeholder="请输入联系电话" clearable />
							</el-form-item>
							<el-form-item label="工作时间" prop="workingHours">
								<el-input v-model="formData.workingHours" placeholder="例如：9:00-18:00" clearable />
							</el-form-item>
							<el-form-item label="邮箱" prop="email">
								<el-input v-model="formData.email" placeholder="请输入公司邮箱" clearable />
							</el-form-item>
							<el-row :gutter="20">
								<el-col :span="12" v-if="false">
									<el-form-item label="微信" prop="wechat">
										<upload-img v-model:imageUrl="formData.wechat">
											<template #empty>
												<el-icon class="add-icon"><Plus /></el-icon>
												<span>请上传微信</span>
											</template>
										</upload-img>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="公司logo" prop="logo">
										<upload-img v-model:imageUrl="formData.logo">
											<template #empty>
												<el-icon class="add-icon"><Plus /></el-icon>
												<span>请上传公司logo</span>
											</template>
										</upload-img>
									</el-form-item>
								</el-col>
							</el-row>

							<div class="location-info">
								<h3><i class="el-icon-location"></i> 地理位置信息</h3>
								<el-form-item label="公司地址" prop="address">
									<el-input v-model="formData.address" placeholder="请输入公司地址或点击地图选择" clearable />
								</el-form-item>
								<div class="location-grid">
									<div>
										<el-form-item label="经度" prop="longitude">
											<el-input v-model="formData.longitude" placeholder="经度" clearable />
										</el-form-item>
									</div>
									<div>
										<el-form-item label="纬度" prop="latitude">
											<el-input v-model="formData.latitude" placeholder="纬度" clearable />
										</el-form-item>
									</div>
								</div>
								<span class="talert">提示：点击地图设置位置，或搜索地点进行定位</span>
							</div>
						</div>
					</el-col>
					<el-col :span="12">
						<div class="map-container">
							<div class="company-map" id="companyMap"></div>
							<div class="map-controls">
								<el-input class="search-input" v-model="searchKeyword" placeholder="搜索地点..." @keyup.enter="handleSearch" clearable>
									<template #suffix>
										<div class="search-icon" @click="handleSearch">
											<el-icon class="el-input__icon"><search /></el-icon>
										</div>
									</template>
								</el-input>
								<!-- <el-button type="primary" @click="handleSearch"> 搜索 </el-button> -->
							</div>
							<div class="map-tips">
								<el-alert v-if="markerPosition" :title="'当前位置：' + markerPosition" type="success" />
							</div>
						</div>
					</el-col>
				</el-row>
			</el-card>
			<el-card>
				<template #header>
					<div class="card-header">
						<span>公司简介</span>
					</div>
				</template>
				<el-form-item label="" prop="introduction">
					<editor v-model:get-html="formData.introduction" height="500px" />
				</el-form-item>
			</el-card>
			<div class="button-box"></div>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { loadBaiduMap } from '/@/utils/baiduMapLoader.js'; // 根据你的路径调整
import { getObj, addObj, putObj, fetchList } from '/@/api/qytest/sysCompanyInfo';
import { useMessage } from '/@/hooks/message';
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
const searchKeyword = ref('');
const markerPosition = ref('');
// 提交表单数据
const formData = reactive({
	id: '',
	companyName: '',
	address: '',
	contactPhone: '',
	workingHours: '',
	email: '',
	wechat: '',
	// 公司简介 (富文本HTML内容)
	introduction: '',
	longitude: '',
	latitude: '',
	logo: '',
});

// 定义校验规则
const rules = reactive({
	companyName: [{ required: true, message: '请输入 公司名称', trigger: 'blur' }],
	address: [{ required: true, message: '请输入 公司地址', trigger: 'blur' }],
	contactPhone: [
		{ required: true, message: '请输入 联系电话', trigger: 'blur' },
		{ pattern: /^([0-9]{3,4}-)?[0-9]{7,8}$|^\d{3,4}-\d{3,4}-\d{3,4}$|^1[0-9]{10}$/, message: '请输入正确的手机或电话号码', trigger: 'blur' },
	],
	workingHours: [{ required: true, message: '请输入 工作时间', trigger: 'blur' }],
	email: [
		{ required: true, message: '请输入 邮箱', trigger: 'blur' },
		{ type: 'email', message: '请输入 正确的邮箱格式', trigger: 'blur' },
	],
	wechat: [{ required: true, message: '请上传 微信二维码', trigger: 'change' }],
	logo: [{ required: true, message: '请上传 公司logo', trigger: 'change' }],
	longitude: [{ required: true, message: '请输入 经度 或者 地图选点', trigger: 'blur' }],
	latitude: [{ required: true, message: '请输入 纬度 或者 地图选点', trigger: 'blur' }],
	introduction: [
		{
			validator: (rule: any, value: any, callback: any) => {
				callback(isEditorEmpty(value) ? '产品详情 不能为空' : undefined);
			},
			trigger: 'change',
		},
	],
});
const isEditorEmpty = (html: any) => {
	if (!html) return true;
	// 创建临时DOM元素解析HTML
	const tempDiv = document.createElement('div');
	tempDiv.innerHTML = html;
	// 检查是否存在有效内容
	const hasContent = tempDiv.textContent
		? tempDiv.textContent.trim() !== '' || // 文本内容
			tempDiv.querySelectorAll('img, video, iframe').length > 0
		: false; // 非文本内容
	return !hasContent;
};
// 地图方法汇总
let map = null;
let geocoder = null;
let localSearch = null;
const initMap = async () => {
	try {
		// 等待百度地图加载
		await loadBaiduMap();

		// 创建地图实例
		map = new BMapGL.Map('companyMap');
		geocoder = new BMapGL.Geocoder();

		// 检查是否有初始坐标
		if (formData.longitude && formData.latitude) {
			const point = new BMapGL.Point(parseFloat(formData.longitude), parseFloat(formData.latitude));
			map.centerAndZoom(point, 16);
			reverseGeocode(point);
		} else {
			// 默认位置 - 北京
			const point = new BMapGL.Point(116.404, 39.915);
			map.centerAndZoom(point, 11);
		}
		map.enableScrollWheelZoom(true);
		// 初始化本地搜索
		localSearch = new BMapGL.LocalSearch(map, {
			renderOptions: { map: map, autoViewport: true },
			pageCapacity: 5,
			onSearchComplete: (results) => {
				if (localSearch.getStatus() === BMAP_STATUS_SUCCESS) {
					for (let i = 0; i < results.getCurrentNumPois(); i++) {
						const poi = results.getPoi(i);
						// 只取第一个结果
						if (i === 0) {
							map.centerAndZoom(poi.point, 16);
							reverseGeocode(poi.point);
						}
					}
				} else {
					ElMessage.error('未找到相关地点，请尝试其他关键词');
				}
			},
		});
		// 点击地图添加标记
		map.addEventListener('click', function (e) {
			const point = new BMapGL.Point(e.point.lng, e.point.lat);
			// reverseGeocode(point);
			// 填充表单数据
			formData.longitude = point.lng.toFixed(6);
			formData.latitude = point.lat.toFixed(6);
		});
	} catch (error) {
		console.error(error);
		alert('地图加载失败，请检查网络或刷新页面');
	}
};
// 逆地理编码获取地址
const reverseGeocode = (point) => {
	geocoder.getLocation(point, (result) => {
		if (result) {
			formData.address = result.address;
			markerPosition.value = result.address;
		}
	});
};

// 处理搜索
const handleSearch = () => {
	if (!searchKeyword.value.trim()) {
		ElMessage.warning('请输入搜索关键词');
		return;
	}

	localSearch.search(searchKeyword.value);
};
// 初始化始数据
const init = () => {
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	loading.value = true;
	fetchList({ current: -1 })
		.then((res: any) => {
			const data = res.data.records;
			if (data && data.length) {
				const form = data[0];
				Object.assign(formData, form);
			}
		})
		.finally(() => {
			loading.value = false;
		});
};
// 提交表单
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return ElMessage.error('请填写所有必填字段');

	try {
		loading.value = true;
		formData.id ? await putObj(formData) : await addObj(formData);
		useMessage().success(formData.id ? '修改成功' : '添加成功');
	} catch (err: any) {
	} finally {
		loading.value = false;
	}
};
onMounted(async () => {
	await init();
	await initMap(); // 调用地图初始化方法
});
</script>

<style scoped lang="scss">
.layout-padding {
	overflow: auto;
	position: relative;
	padding-bottom: 80px; /* 添加底部内边距防止内容被按钮遮挡 */
}
.el-card {
	margin-bottom: 12px;
}

.map-container {
	position: relative;
	border-radius: 8px;
	overflow: hidden;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	height: 580px;
	.company-map {
		width: 100%;
		height: 100%;
		background: #f0f2f5;
	}
	// 搜索
	.map-controls {
		position: absolute;
		top: 20px;
		left: 20px;
		right: 20px;
		z-index: 1000;
		display: flex;
		gap: 10px;
		.search-input {
			flex: 1;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		}
	}
	.map-tips {
		position: absolute;
		bottom: 20px;
		left: 0;
		right: 0;
		text-align: center;
		z-index: 1000;
		.el-alert {
			display: inline-flex;
			max-width: 90%;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
		}
	}
}
// 地理位置坐标
.location-info {
	background: white;
	padding: 15px;
	border-radius: 8px;
	margin-top: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	h3 {
		margin-bottom: 12px;
		color: #409eff;
		font-weight: 500;
	}
	.location-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 15px;
		margin-bottom: 12px;
	}
}
.talert {
	color: #666;
	font-size: 13px;
	padding-left: 26px;
}

/* 按钮容器样式 */
// .card-header {
// 	display: flex;
// 	justify-content: space-between;
// }
.search-icon {
	cursor: pointer;
	height: 100%;
}
</style>
